package org.dh2580.netty.demo.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: hao.deng
 * @Date: 2019/3/20-下午2:48
 */
public class TimeClient {
    public static void main(String[] args) throws Exception {
        new Thread(new TimeClientHandler("127.0.0.1", 8080)).start();
    }

    public static class TimeClientHandler implements Runnable {
        private String host;
        private int port;
        private Selector selector;
        private SocketChannel socketChannel;

        private volatile boolean stop;

        public TimeClientHandler(String host, int port) throws Exception {
            this.host = host;
            this.port = port;

            //创建选择器
            selector = Selector.open();

            //创建客户端Channel，并发起连接
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            boolean connectSuccess = socketChannel.connect(new InetSocketAddress(host, port));
            if (connectSuccess) {
                //注册客户端Channel到Selector
                socketChannel.register(selector, SelectionKey.OP_READ);
                //发送数据
                doWrite(socketChannel);
            } else {
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
            }
        }

        private void doWrite(SocketChannel socketChannel) throws Exception {
            byte[] request = "QUERY TIME ORDER".getBytes();

            //将请求数据封装到Buffer中
            ByteBuffer writeBuffer = ByteBuffer.allocate(request.length);
            writeBuffer.put(request);
            writeBuffer.flip();

            //发送数据
            socketChannel.write(writeBuffer);
        }

        @Override
        public void run() {
            try {
                innerRun();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void innerRun() throws Exception {
            while (!stop) {
                //选择已就绪的key等待3000ms
                selector.select(3000);
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectedKeys.iterator();

                while (it.hasNext()) {
                    SelectionKey key = it.next();

                    //处理响应的key
                    handleInput(key);

                    it.remove();
                }
            }

            if (selector != null) {
                selector.close();
            }
        }

        private void handleInput(SelectionKey key) throws Exception {
            if (!key.isValid()) {
                return;
            }

            if (key.isReadable()) {
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = socketChannel.read(readBuffer);

                if (readBytes <= 0) {
                    return;
                }

                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);

                String body = new String(bytes, "UTF-8");
                System.out.println("Now is " + body);

                stop = true;
            }

            if (key.isConnectable() && socketChannel.finishConnect()) {
                socketChannel.register(selector, SelectionKey.OP_READ);
                doWrite(socketChannel);
            } else {
                System.exit(0);
            }
        }
    }

}
